<template>
	<view class="imgList" style=" color: #333;" v-if="show&&(!hide)">
		<view :style="[style]" v-for="(item,index) in list" :key="index" class="pr imgBox border">
			<video class="w-max h-max" :src="item.path" v-if="type=='video'" :controls="false"></video>
			<image class="w-max h-max" v-else :src="item.path||item" mode="aspectFill"></image>
			<view @tap.stop="del(index)" v-if="!disabled" class="close pa">×</view>
		</view>
		<view :style="[style]" v-if="(!disabled)&&list.length<max*1" class="border imgBox" @tap="setimg()"
			style="text-align: center;line-height: 1em;">
			<view :style="{fontSize:size/3+'rpx'}">+</view>
			<view :style="{fontSize:size/7+'rpx'}">上传{{type=='video'?'视频':'照片'}}</view>
		</view>
	</view>
</template>

<script>
import $config from '@/api/http.baseUrl.js';
	/**
	 * img-list 探迹图片上传组件
	 * @description 此组件一般用图片上传。
	 * @tutorial 张浩
	 * @property {String} size 图片大小 单位rpx 默认200
	 * @property {String} disabled 图片大小 单位rpx 默认200
	 * @property {String} max 最大上传图片数量 默认1
	 * @property {String} ids 回显 图片id 
	 * @property {String} paths 回显 图片链接
	 * @property {String} type 上传视频 video 上传图片 img 默认img 
	 * @property {Boolean} show 是否隐藏组件 默认true  
	 * @property {Boolean} hide 是否隐藏组件 默认false  
	 * @property {function} @success 获取ids 
	 * @example <imgList @success="ids=>form.id=ids"></imgList> //最常用 只取 id
	 * @example @click="$refs.img.uplode('getImg')" <imgList ref="img" @getImg="e=>{form.id=e.id,form.path_url=e.path}"></imgList>
	 */
	export default {
		name: "imgList",
		props: {
			size: { //图片大小
				default: '200',
			},
			max: { //上传图片数量
				default: 1
			},
			ids: { //回显id
				default: '',
			},
			paths: { //回显图片
				default: '',
			},
			type: {
				default: 'img', //video  视频
			},
			show: {
				default: true, //是否隐藏组件 默认true  
			},
			hide: {
				default: false, //是否隐藏组件 默认false  
			},
			disabled:{
				default: false, //是否阻止操作 默认false
			}
		},
		computed: {
			style() {
				return {
					"width": this.size + 'rpx',
					"height": this.size + 'rpx'
				}
			}
		},
		data() {
			return {
				list: [], //内部显示的图片数组 [{id:1,path:'https//img.png'}]
			};
		},
		watch: {
			ids(val1, val2) {
				this.setInit()
			},
			paths(val1, val2) {
				this.setInit()
			}
		},
		created() {
			this.setInit()
		},
		methods: {
			setInit() {
				let paths = this.paths
				let ids = this.ids
				if (!ids) return //判断有没有传id
				if (!paths) return //判断有没有传回显地址
				if (this.list.length) return //判断现在是否有值
				if (!Array.isArray(paths)) paths = [paths]
				ids = ids.toString() //id先转字符串
				ids = ids.split(',') //以','分割
				this.list = ids.map((item, index) => {
					return { //回显到内部
						id: item,
						path: paths[index]
					}
				})
				this.success()
			},
			setimg() {
				if (this.type == "video") { //视频
					this.upVideo().then(res => {
						let item = {}
						item.id = res.id
						item.path = res.path
						this.list.push(item)
						this.success()
					})
				} else {
					let count = this.max - this.list.length
					this.$off('up')
					this.$on('up', res => {
						let item = {}
						item.id = res.id
						item.path = res.path
						this.list.push(item)
						this.success()
					})
					this.upload('up', count)
				}
			},
			del(index) {
				let that = this
				uni.showModal({
					title: '删除',
					content: "确认删除吗",
					success(res) {
						if (res.confirm) {
							that.list.splice(index, 1)
							that.success()
						}
					}
				})
			},
			success() {
				let ids = this.list.map(item => {
					return item.id
				})
				ids = ids.toString()
				this.$emit('success', ids, this.list)
			},

			upload(emit = '', count = 1) {
				if (!emit) {
					uni.showToast({
						title: '请使用uni.$on接收',
						icon: "none"
					})
					return
				}
				let that = this
				uni.chooseImage({
					count, //最多可以选择的图片张数，默认9
					success(e) {
						e.tempFilePaths.map(item => {
							uploadFile(item)
						})
					}
				})
				let uploadFile = (filePath) => {
					uni.uploadFile({
						header: {
							Authorization: uni.getStorageSync('token') || ''
						},
						url: `${$config.baseUrl}/system/basic/postUploadOne`, //仅为示例，非真实的接口地址
						filePath,
						fileType: "image",
						name: 'img',
						success: (res) => {
							res = JSON.parse(res.data)
							this.$emit(emit, res)
						},
						complete() {
							uni.hideLoading()
						}
					});
				}
			},
			upVideo() { //上传视频
				let that = this
				return new Promise((resolve, reject) => {
					uni.chooseVideo({
						// sourceType: ['camera', 'album'],//album 从相册选视频，camera 使用相机拍摄，默认为：['album', 'camera']
						success(e) {
							console.log(e);
							uni.showLoading()
							let filePath = e.tempFilePath
							uni.uploadFile({
								header: {
									Authorization: uni.getStorageSync('token') || ''
								},
								url: that.$baseUrl +
									'/system/basic/postUploadOne', //仅为示例，非真实的接口地址
								filePath,
								// fileType: "image",//文件类型，image/video/audio 仅支付宝小程序，且必填。
								name: 'img', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
								formData: {
									type: 'file'
								},
								success: (res) => {
									if (res.data) {
										res = JSON.parse(res.data)
										resolve(res)
									} else {
										reject(res)
									}
								},
								complete() {
									uni.hideLoading()
								}
							});
						}
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	.imgList {
		box-sizing: border-box;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		align-items: center;

		margin-right: -10rpx; //////////
	}

	.imgBox {
		margin: 10rpx;

		margin: 0 10rpx 10rpx 0; //////////

		display: flex;
		flex-direction: column;
		justify-content: space-evenly;
		align-items: center;
		border-radius: 10rpx;
		color: #606266;
	}

	.border {
		border: #dddddd dashed 2rpx;
	}

	.close {
		top: -8rpx;
		right: -8rpx;
		border-radius: 50%;
		line-height: 30rpx;
		width: 30rpx;
		height: 30rpx;
		text-align: center;
		color: #fff;
		background: red;
		// z-index: 1;
	}

	.pa {
		position: absolute;
	}

	.pr {
		position: relative;
	}

	.w-max {
		width: 100%;
	}

	.h-max {
		height: 100%;
	}
</style>
